import 'package:flutter/material.dart';
import 'package:flutter_mvvm_demo/base/base_state.dart';
import 'package:flutter_mvvm_demo/page/home/model/home_product_model.dart';
import 'package:flutter_mvvm_demo/page/home/view/product_view.dart';
import 'package:flutter_mvvm_demo/page/home/view_model/home_view_model.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends BaseState<HomePage, HomeViewModel> {
  @override
  void initState() {
    super.initState();
    pageName = "首页";
    viewModel = HomeViewModel(context);
    viewModel.refreshData(isShowLoading: true);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider.value(
      value: viewModel,
      child: Scaffold(
        appBar: AppBar(
          title: const Text("首页"),
        ),
        body: initView(),
      ),
    );
  }

  @override
  Widget buildView() {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      controller: viewModel.refreshController,
      onRefresh: () {
        viewModel.page = 0;
        viewModel.refreshData(isShowLoading: true);
        debugPrint("======正在下拉刷新");
      },
      onLoading: () {
        viewModel.refreshData(isShowLoading: false);
        debugPrint("======正在上拉加载");
      },
      child: ListView.builder(
        padding: const EdgeInsets.symmetric(vertical: 10),
        itemCount: viewModel.dataList.length,
        itemBuilder: (ctx, idx) {
          HomeProductModel model = viewModel.dataList[idx];
          return ProductView(model: model);
        },
      ),
    );
  }
}
